import json
from decimal import Decimal


class Page:
    page = 1
    size = 15
    offset = 0
    start = 0
    end = 15

    def __init__(self, page=0, size=0):
        if page > 0:
            self.set_page(page)
        if size > 0:
            self.set_size(size)

    def set_page(self, val):
        i_val = int(val)
        if i_val > 0:
            self.page = i_val
        self.set_offset()

    def set_size(self, val):
        i_val = int(val)
        if i_val > 0:
            self.size = i_val
        self.set_offset()

    def set_offset(self):
        self.offset = (self.page - 1) * self.size
        self.start = self.offset
        self.end = self.offset + self.size

    def get_limit(self):
        return ' limit %s,%s' % (self.offset, self.size)


class RawJsonForm:
    dataset = None

    def __init__(self, body):
        try:
            self.dataset = json.loads(body)
        except Exception:
            self.dataset = {}

    def get(self, field, default='', auto_trim=True):
        val = default
        if field in self.dataset:
            val = self.dataset[field]
        val_typ = type(val)
        if val_typ is int:
            val = str(val)
        elif val_typ is float:
            val = str(val)
        elif val_typ is str and auto_trim:
            val = val.strip()
        return val

    def get_int(self, field, default=0):
        val = _val = default
        if field in self.dataset:
            _val = self.dataset[field]
            try:
                val = int(_val)
            except:
                pass
        return val

    def get_dec(self, field, default=Decimal('0')):
        val = _val = default
        if field in self.dataset:
            try:
                _val = str(self.dataset[field])
                val = Decimal(_val)
            except:
                pass
        return val

    def get_list(self, field, default=None):
        if default is None:
            default = []
        val = _val = default
        if field in self.dataset:
            _val = self.dataset[field]
        elif field == '':
            _val = self.dataset
        typ = type(_val)
        if typ is list:
            val = _val
        return val

    def get_page(self):
        page = Page()
        if 'page' in self.dataset:
            page.set_page(self.get_int('page'))
        if 'size' in self.dataset:
            page.set_size(self.get_int('size'))
        return page
